<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/15
 * Time: 18:03
 */
namespace app\common\lib\task;
use app\common\lib\ali\Sms;
use app\common\lib\redis\Predis;
use app\common\lib\Redis;

class Task
{
    /**
     * @todo 异步发送短信
     * @param $data
     * @param $serv swoole对象
     * @return bool
     */
    public function sendSms($data, $serv)
    {
        try{
            $result = Sms::sendSms($data['phone'], $data['code']);
        }catch (\Exception $e){
            //todo
            return false;
            //echo $e->getMessage();
        }
        //如果发送成功，把验证码记录到redis里面
        if($result->Code === 'OK'){
            //发送成功，将验证码存入redis
            /*
            $redis = new \Swoole\Coroutine\Redis();
            $redis->connect(config('redis.host'), config('redis.port'));
            $redis->auth(config('redis.password'));
            $redis->set(Redis::smsKey($phone_num), $code, config('redis.out_time'));*/
            Predis::getInstance()->set(Redis::smsKey($data['phone']), $data['code'], config('redis.out_time'));
        }else{
            return false;
        }
        return true;
    }


    /**
     * @todo 异步task推送文字直播数据
     * @param $data
     * @param $serv
     */
    public function pushLive($data, $serv)
    {
        /*
        $clients = Predis::getInstance()->sMembers(config('redis.live_game_key'));

        foreach($clients as $fd){
            $serv->push($fd, json_encode($data));
        }*/
        foreach($serv->ports[0]->connections as $fd){
            if($serv->exist($fd)){
                $serv->push($fd, json_encode($data));
            }
        }
    }

    /**
     * @todo 异步task推送聊天室内容
     * @param $data
     * @param $serv
     */
    public function pushChat($data, $serv)
    {
        //connection_list
        foreach($serv->ports[1]->connections as $fd)
        {
            if($serv->exist($fd)) {
                $serv->push($fd, json_encode($data));
            }
        }
    }
}